// 这个东西是和InfiniteContainer中的refreshHintBox有强耦合关系的，使用必须把refreshHintBox复制到要用的页面
// (不要忘记复制样式)，且页面中要有$refs.scrollView 作为监听下拉的容器
export default {
  data (){
    return {
      refreshHintBoxHeight: 0,
      refreshHintBoxText: '下拉刷新',
      swipeDownRefreshStatus: 1,

      heightAnimated: false
    }
  },

  mounted (){
    // 下拉刷新实现
    if(this.swipeDownRefreshMethod){
      var scrollView = this.$refs.scrollView.$el

      var start = 0

      scrollView.addEventListener('touchstart', e =>{
        e.stopPropagation()
        if(this.swipeDownRefreshStatus !== 1 || scrollView.scrollTop !== 0){ return }

        start = e.touches[0].clientY
      })

      scrollView.addEventListener('touchmove', e =>{
        this.swipeDownRefreshMoveEventDisabled && e.preventDefault()
        e.stopPropagation()
        if(this.swipeDownRefreshStatus !== 1 || scrollView.scrollTop !== 0){ return }

        var point = e.touches[0].clientY
        var diff = point - start
        this.refreshHintBoxHeight += diff > 10 ? 10 : diff
        start = point

        if(this.refreshHintBoxHeight >= 100){
          this.refreshHintBoxHeight = 100
        }
      })

      scrollView.addEventListener('touchend', e =>{
        e.stopPropagation()
        if(this.swipeDownRefreshStatus !== 1 || scrollView.scrollTop !== 0){ return }

        // 触摸结束后，如果touchmove处于禁用状态，则设置scrollY = 1，解除禁用
        // 为什么不直接将swipeDownRefreshMoveEventDisabled设置为false：这样做会出现scrollY为0，且touchmove未禁用，
        // 又会出现微信网页下拉刷新失效的问题
        this.swipeDownRefreshMoveEventDisabled && scrollView.scrollTo(0, 1)

        this.heightAnimated = true

        if(this.refreshHintBoxHeight >= 100){
         
          this.swipeDownRefreshStatus = 2
          this.refreshHintBoxText = '刷新中'
          
          this.$nextTick(() => this.refreshHintBoxHeight = 70) 

          this.swipeDownRefreshMethod()
          .finally(() => {
            setTimeout(() =>{
              start = 0
              this.refreshHintBoxHeight = 0

              setTimeout(() =>{
                this.swipeDownRefreshStatus = 1
                this.heightAnimated = false
                this.refreshHintBoxText = '下拉刷新'
              }, 301)
            }, 1500)
          })
          .then(() =>{
            this.swipeDownRefreshStatus = 3
            this.refreshHintBoxText = '刷新完成'
          })
          .catch(() =>{
            this.swipeDownRefreshStatus = 0
            this.refreshHintBoxText = '刷新失败'
          })
        }else{
          start = 0
          this.refreshHintBoxHeight = 0
          setTimeout(() =>{
            this.heightAnimated = false
            this.refreshHintBoxText = '下拉刷新'
          }, 100)
        }
      })
    }
  }
}